<?php
/**
 * @author Aleske A. Evdokimov <ale@izhcat.ru>
 * @version $Id: downloader.php 16 2009-04-23 12:04:35Z workales $
 */

define('CSV_SEPARATOR', ';');
define('CSV_ESCAPE', '"');

function help() {
  global $argv;

  echo <<<EOT
Usage:
  php $argv[0] CSVFILENAME.csv /path/to/output/files FIELDNUMBER [--prefix=PREFIX]

Parameters:

  CSVFILENAME.csv
    Name of the CSV file with download queue list

  /path/to/output/files
    Name of directory to place downloaded files. MUST be writeable. To specify the current
    directory, use . (single period)

  FIELDNUMBER
    Field number of filename in CSV
    NB! Fields are numbered from zero

Switches:

  --prefix=PREFIX
    Append specified prefix to output filename

Examples:
  php $argv[0] ./satlist.csv ./testdata 3
  php $argv[0] ./pkglist.csv ./testdata 0 --prefix=pkg_

EOT;

  exit(1);
}

if ($argc < 4) help();

$path = $argv[2];

if (!is_dir($path) && !is_writable($path)) help();

$refname = $argv[1];

@$F = fopen($refname, "r");
if (!$F) help();

$field = (int)$argv[3];

$prefix = (substr($argv[4], 0, 9) == '--prefix=') ? substr($argv[4], 9) : '';

while (($str = fgetcsv($F, 0, CSV_SEPARATOR, CSV_ESCAPE)) !== false)
  if (array_key_exists($field, $str)) {
    $source = $str[$field];

    @$D = fopen($source, "r");
    if ($D) {
      $c = stream_get_contents($D);
      fclose($D);

      $E = fopen($path . DIRECTORY_SEPARATOR . $prefix . basename($source), "w");
      fwrite($E, $c);
      fclose($E);
    }
  }

fclose($F);

exit(0);
